import json

from django import http
from django.core.cache import cache
from django.shortcuts import render

# Create your views here.
from django .views import View

from areas.models import Area
from meiduo.utils.mixn import AuthenticateView
from meiduo.utils.response_code import RETCODE
from users.models import Address

# 地址展示
# 只有登录用户才能进行地址展示
class AddressesView(AuthenticateView):
    def get(self,request):
        # 既然时登录用户，肯定都时会有user的
        user = request.user
        # 查询出没有逻辑删除，且是当前用户的收货地址
        data = Address.objects.filter(user=user,is_deleted=False)
        addresses=[]
        for i in data:
            #撞到一个字典里面好做展示
            address_dict = {
                "id":i.id,
                "title": i.title,
                "receiver": i.receiver,
                "province": i.province.name,
                "province_id": i.province_id,
                "city": i.city.name,
                "city_id": i.city_id,
                "district_id": i.district_id,
                "district": i.district.name,
                "place": i.place,
                "mobile": i.mobile,
                "tel": i.tel,
                "email": i.email}
            addresses.append(address_dict)

        context = {
                'addresses': addresses,
                'default_address_id': user.default_address_id
            }
        return render(request,"user_center_site.html",context)
# 省市区选择
class AreasView(AuthenticateView):
    def get(self,request):
        parent_id = request.GET.get("area_id")
        if parent_id:
            # TODO 把数据存储到Django默认缓存里面
            area_lists = cache.get("area_lists%s"%parent_id)
            parent_model=Area.objects.get(id=parent_id)
            if not area_lists:

                data = Area.objects.filter(parent_id=parent_id)
                area_lists = []
                for i in data:
                    area_lists.append({"name":i.name,
                                       "id":i.id})
                cache.set("area_lists%s"%parent_id,area_lists,3600)
            sub_data = {
                'id': parent_model.id,
                'name': parent_model.name,
                'subs': area_lists
            }
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})


        else:
            area_list = cache.get("area_list")
            if  area_list is None:
                data = Area.objects.filter(parent_id__isnull=True)
                area_list =[]
                for i in data:
                    area_list.append({"name":i.name,
                                      "id":i.id})
                cache.set("area_list",area_list,3600*2)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': area_list})

# 新增地址
class AddreCreate(AuthenticateView):
    def post(self,request):
        # 从请求中获取需要新增的数据
        user =request.user
        data = json.loads(request.body.decode())
        title=data.get('title')
        receiver=data.get('receiver')
        province_id=data.get('province_id')
        city_id=data.get('city_id')
        district_id=data.get('district_id')
        place=data.get('place')
        mobile=data.get('mobile')
        tel=data.get('tel')
        email=data.get('email')
        if all([title,receiver,province_id,city_id,district_id,place,mobile]) is False:
            return http.HttpResponseForbidden("数据不齐全")
        # 现在我要查出所有为逻辑删除的当前用户的地址
        if Address.objects.filter(user=user,is_deleted=False).count()<20:
            address = Address.objects.create(
                user=user,
                title=title,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            address_dict = {
                'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province_id': address.province_id,
            'province': address.province.name,
            'city_id': address.city_id,
            'city': address.city.name,
            'district_id': address.district_id,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,}

            if((user.default_address_id) is None or (Address.objects.filter(user=user,is_deleted=False,id=user.default_address_id).count()))==0:

                user.default_address = address
                user.save()
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address': address_dict})
        else:
            return http.HttpResponseForbidden('用户收货地址上限')

class DefaultView(AuthenticateView):
    def put(self, request, address_id):
        """实现默认地址"""
        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('要修改的地址不存在')

        user = request.user
        user.default_address = address
        user.save()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

class UpdateAddresView(AuthenticateView):
    def put(self,request,address_id):
        user = request.user

        data = json.loads(request.body.decode())
        id = address_id
        title = data.get('title')
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        if all([title, receiver, province_id, city_id, district_id, place, mobile]) is False:
            return http.HttpResponseForbidden("数据不齐全")
        ares = Address.objects.get(user=user,id=id)
        ares.tel=tel
        ares.email =email
        ares.title =title
        ares.receiver =receiver
        ares.province_id =province_id
        ares.city_id =city_id
        ares.district_id =district_id
        ares.place =place
        ares.mobile =mobile
        ares.save()

        address = Address.objects.get(id=id)  # 要重新查询一次新数据
        # 把新增的地址数据响应回去
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province_id': address.province_id,
            'province': address.province.name,
            'city_id': address.city_id,
            'city': address.city.name,
            'district_id': address.district_id,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address': address_dict})
    def delete(self,request,address_id):
        addres = Address.objects.get(id=address_id)
        addres.is_deleted=True
        addres.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
class UpdateTitleView(AuthenticateView):
    def put(self,request,address_id):

        addres = Address.objects.get(id=address_id)
        addres.title=json.loads(request.body.decode()).get("title")
        addres.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})